package com.aiwiown.snackmq.storage.index;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;

/**
 * Represents an index entry. This class is designed to be compatible with
 * two different indexing strategies used in the system.
 */
@Data
@AllArgsConstructor
public class IndexEntry implements Serializable {

    private static final long serialVersionUID = -4425722023910943598L;

    // --- Fields for the full, Message-ID based index (used by IndexFile) ---
    private String messageId;
    private int fileIndex;
    private long timestamp;

    // --- Compatibility for the simple, offset-based index (used by Index.java) ---

    /**
     * The size of a simple index entry (logical offset -> physical position) in bytes.
     * This is for the sparse index used by LogSegment/Index.
     * long (8 bytes for logical offset) + int (4 bytes for physical position).
     */
    public static final int SIZE = Long.BYTES + Integer.BYTES; // 8 + 4 = 12 bytes;
    private final long offset; // In this context, it's the physical position in the data file
    private final int position;

    public IndexEntry(String messageId, int fileIndex, long offset, int position, long timestamp) {
        this(offset, position);
        this.messageId = messageId;
        this.fileIndex = fileIndex;
        this.timestamp = timestamp;

    }

    /**
     * A constructor for the simple, offset-based index used by the Index class.
     *
     * @param logicalOffset    The logical offset of the message.
     * @param physicalPosition The physical position in the log file.
     */
    public IndexEntry(long logicalOffset, int physicalPosition) {
        // We are re-purposing the fields for this simple use case.
        this.offset = logicalOffset;
        // Using 'length' to hold the physical position to avoid adding more fields.
        this.position = physicalPosition;
    }

    /**
     * Gets the physical position for the simple index case.
     * This is needed by LogSegment.
     *
     * @return The physical position in the log file.
     */
    public int getPosition() {
        // In the simple index case, we stored the position in the 'length' field.
        return this.position;
    }

    /**
     * Alias for getOffset() to satisfy calls to getStartPosition().
     *
     * @return The physical starting position in the log file.
     */
    public long getStartPosition() {
        return this.offset;
    }
}